package org.example.springbootblog.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Slf4j
public class JwtUtil {
    private static final String secret = "FzG6p48J80L6vFxLrQqy2JVN27NiYbgjtGuYCTpeX7w=";
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));

//    private static final long expiration = 24*60*60*1000;
    private static final long expiration = 60*60*1000;
    //1.生成token
    public static String genToken(Map<String, Object> map){
        return Jwts.builder()
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis()+expiration))
                .setIssuedAt(new Date())
                .signWith(key)
                .compact();
    }

    //2.校验token
    public static Claims parseToken(String token){
        if (!StringUtils.hasLength(token)){
            return null;
        }
        //jwt解析器
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims body = null;
        try{
            body = build.parseClaimsJws(token).getBody();
            return body;
        }catch (ExpiredJwtException e){
            log.error("token过期, token:{}", token);
        }catch (SignatureException e){
            log.error("签名不匹配, token:{}", token);
        }catch (Exception e){
            log.error("token解析失败, token: {}", token);
        }
        return null;
    }
}
